﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace editor.cfg
{
    public class ENUM
    {
        public Defines Defines { get; private set; }
        public string Namespace { get; private set; }
        public string SimpleName { get; private set; }
        public string FullName { get; private set; }

        public List<string> Cases { get; private set; }

        public Dictionary<string, string> Alias { get; private set; }

        public bool IsValid(string enumName)
        {
            return Alias.ContainsKey(enumName);
        }

        public ENUM(Defines ds, string module, XmlElement node)
        {
            this.Defines = ds;
            Namespace = module;
            SimpleName = node.Attributes["name"].Value;
            FullName = module + "." + SimpleName;

            Alias = new Dictionary<string, string>();
            Cases = new List<string>();

            //Cases.Add("NULL");
            //Alias.Add("NULL", "NULL");

            foreach (XmlElement c in node.GetElementsByTagName("var"))
            {
                string name = c.GetAttribute("name");
                if (string.IsNullOrEmpty(name))
                    Err($"case name can't be empty");
                if (Alias.ContainsKey(name))
                    Err($"case name:{name} duplicate");
                //Cases.Add(name);
                Alias.Add(name, name);
                var alias = c.GetAttribute("alias");
                if (string.IsNullOrEmpty(alias))
                {
                    Cases.Add(name);
                    continue;
                }

                if (Alias.ContainsKey(alias))
                    Err($"case alias:{alias} duplicate");
                Alias.Add(alias, name);
                Cases.Add(alias);
            }
            Log.Debug($"enum:{FullName} cases:{string.Join(",", Cases.ToArray())}");
        }

        public string ToFirstAliasNameOrDefault(string caseName)
        {
            if (Alias.TryGetValue(caseName, out var v))
            {
                return Cases.First(c => Alias[c] == v);
            }
            else
            {
                return Cases[0];
            }
        }

        private void Err(string msg)
        {
            throw new Exception($"enum:{FullName} {msg}");
        }
    }
}
